package cn.codergege.shiro.controller;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.codergege.shiro.service.Md5Update;
import cn.codergege.shiro.service.ShiroService;

@Controller
@RequestMapping("/shiro")
public class LoginHandler {

	private final Logger log = LoggerFactory.getLogger(LoginHandler.class);

	@Resource
	private Md5Update md5Update;
	
	@Resource
	private ShiroService shiroService;

	@RequestMapping("/testShiroAnnotation")
	public String ktestShiroAnnotation() {

		shiroService.testMethod();
		
		log.info("是否有 admin 角色: " + SecurityUtils.getSubject().hasRole("admin"));
		
		return "forward:/list.jsp";
	}

	@RequestMapping("/login")
	public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
		// 获取 subject
		Subject subject = SecurityUtils.getSubject();
		if (!subject.isAuthenticated()) {
			// 封装 token
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// rememberme
			token.setRememberMe(true);
			try {
				subject.login(token);
			} catch (AuthenticationException e) {
				log.info("登录失败:　" + e.getLocalizedMessage());
			}
		}
		return "redirect:/list.jsp";
	}
	
	@RequestMapping("/md5update")
	public String md5UpdateHandler() {
		try {
			md5Update.update();
		} catch (Exception e) {
			e.printStackTrace();
			log.info("更新加密密码时异常: " + e.getMessage());
		}
		return "redirect:/list.jsp";
	}
}
